<template>

  <el-dialog v-model="pickRangeDialog" title="预定时间选择" width="700">
    <div>
      <a style="color: darkred">* 不可选的日期为已被预约的日期</a>
    </div>
    <div class="demo-date-picker">
      <div class="block">
        <el-date-picker
            @change="timeRangeChange"
            v-model="timeRange"
            type="daterange"
            range-separator="To"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            size="large"
            :disabledDate="disabledDate"
        />
      </div>
    </div>

    <div class="btn-div">
      <el-button style="margin-top: 20px" type="primary" @click="bookingSubmitClick">预约提交</el-button>
    </div>
  </el-dialog>


  <div v-for="(value, key) in listData" :key="key">
    <el-card style="max-width: 100%;margin-top: 20px" shadow="hover">
      <template #header>
        <div style="display: flex;flex-direction: row;align-items: center">
          <div style="display: flex;flex-direction: row;align-items: center">
            <a class="a-title">设备名称：</a>
            <a>{{ value.name }}</a>
          </div>

          <div style="display: flex;flex-direction: row;align-items: center;margin-left: 50px">
            <a class="a-title">设备编号：</a>
            <a>{{ value.code }}</a>
          </div>

          <div style="display: flex;flex-direction: row;align-items: center;margin-left: 50px">
            <a class="a-title">设备型号：</a>
            <a>{{ value.type }}</a>
          </div>

          <div style="display: flex;flex-direction: row;align-items: center;margin-left: 50px">
            <a class="a-title">设备状态：</a>
            <el-tag type="primary" size="large" v-show="value.status === '0'">正常-可预约</el-tag>
            <el-tag type="danger" size="large" v-show="value.status === '1'">维修-不可预约</el-tag>
          </div>
        </div>
      </template>
      <div style="display: flex; flex-direction: row; align-items: center; width: 100%">
        <div v-for="(pic, key) in JSON.parse(value.pic)" :key="key" style="width: 19%">
          <el-image :src="pic.url" style="width: 90%;"/>
        </div>
      </div>


      <template #footer>
        <div style="display: flex;flex-direction: row;align-items: center;justify-content: space-between">
          <div style="display: flex;flex-direction: row;align-items: center">
            <!--            <a>已预约的时间段：</a>-->
            <!--            <a>12:00</a>-->
          </div>
          <el-button type="primary" :disabled="value.status === '1'" @click="bookingClick(value)">预约此设备</el-button>
        </div>

      </template>
    </el-card>
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue'
import {listEquipments} from "@/api/equipment"
import router from "@/router";
import {bookingAdd, listHisByMid} from "@/api/booking";
import store from '@/store'

// 设备使用人预约系统时显示：
// 设备状态
// 设备编号
// 设备名称
// 设备型号
// 设备图片
const listData = ref([])
const pickRangeDialog = ref(false) //选择时间范围弹窗
const timeRange = ref('')
const startT = ref('')
const endT = ref('')
const uId = ref(0)
const nowId = ref(0)
const disabledDates = ref([])

onMounted(() => {
  console.log('onMounted')
  initEquipmentData()
})

const checkRangeByMid = async (mid) => {
  let result = await listHisByMid({
    mid,
  })
  disabledDates.value = result.msg
  console.log('根据Mid查询的返回= ', result)
}

//拿到设备列表
const initEquipmentData = async () => {
  const res = await listEquipments({})
  console.log('设备列表查询的返回： ', res)
  listData.value = res.msg.data
}

const bookingClick = (val) => {
  console.log('预订点击传入', val)
  pickRangeDialog.value = true
  nowId.value = val.id
  checkRangeByMid(nowId.value)
}

const bookingSubmitClick = async () => {
  console.log(timeRange.value)
  if (timeRange.value === null || timeRange.value === '') {
    ElNotification({
      title: 'Warning',
      message: '请选择时间范围',
      type: 'warning',
      duration: 2000,
    })
  } else {
    //拿到时间去数据库中判断是否已经被预约了（查询通过和审核中状态的数据，拒绝的可以不查了）
    startT.value = timeRange.value[0]
    endT.value = timeRange.value[1]
    console.log('预定开始时间', startT.value)
    console.log('预定结束时间', endT.value)
    let result = await bookingAdd({
      uid: store.getters.uid, //用户id
      mid: nowId.value,  //设备id
      start: startT.value,//预约的开始时间
      end: endT.value, //预约的结束时间
      status: 0,
    })

    if (result.error_code === 0) {
      ElNotification({
        title: 'Success',
        message: '预约提交成功',
        type: 'success',
        duration: 1000,
        onClose: () => {
          pickRangeDialog.value = false
          timeRange.value = ''
          disabledDates.value = []
        }
      })
    } else {
    }
  }
}


const timeRangeChange = (val) => {
  console.log('change')
  // 确保选择了两个日期
  if (val && val.length === 2) {
    const startDate = new Date(val[0]);
    const endDate = new Date(val[1]);
    // 检查两个日期之间是否超过30天
    if (endDate - startDate > 2592000000) {
      ElNotification({
        title: 'Warning',
        message: '选择的时间超过了一个月，请重新选择',
        type: 'warning',
        duration: 3000,
      })
      timeRange.value = ''
    }
  }
}

const disabledDate = (time) => {
  // 转换为同一时区以避免时区问题（这里假设所有日期都是UTC+0）
  const now = new Date().setUTCHours(0, 0, 0, 0);
  time.setUTCHours(0, 0, 0, 0); // 去除时分秒，只比较年月日

  // 检查是否早于今天
  if (time < now) {
    return true;
  }

  // 检查是否在禁用日期范围内
  for (const range of disabledDates.value) {
    if (
        time >= new Date(range.start).setUTCHours(0, 0, 0, 0) &&
        time <= new Date(range.end).setUTCHours(23, 59, 59, 999)
    ) {
      return true;
    }
  }

  // 不在禁用范围内，返回false表示可以选择
  return false;
}


</script>


<style scoped>
.a-title {
  font-weight: bold;
}

.demo-date-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
}

.demo-date-picker .block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}

.demo-date-picker .block:last-child {
  border-right: none;
}

.demo-date-picker .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}

.btn-div {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}

</style>